#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command import command
import logging
from utility import tools
from utility.tools import is_checking, check_physical, check_progress

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class AskResultAddAPI(Resource):
    """
    新增问询
    :request: post
    :param ybzzYjdzhx: 夜间端坐呼吸
    :param ybzzKs: 咳嗽
    :param ybzzEx: 恶心
    :param ybzzFl: 乏力
    :param ybzzSfbbs: 上腹部不适
    :param ybzzNxgnyc: 凝血功能异常
    :param ybzzOt: 呕吐
    :param ybzzFg: 发绀
    :param ybzzXs: 消瘦
    :param ybzzXxbjs: 血小板减少
    :param ybzzGzmxyc: 肝脏酶学异常
    :param ybzzCh: 出汗
    :param ybzzYt: 眼突
    :param ybzzDxt: 低血糖
    :param ybzzSszc: 双手震颤
    :param ybzzXm: 胸闷
    :param ybzzFz: 浮肿
    :param ybzzHd: 黄疸
    :param ybzzXj: 心悸
    :param archivesId: 档案ID
    :param checkType: 1 初检 2 常规 3 产后42天
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 参数校验
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            check_res = is_checking(params.get("archivesId"), str(params.get('checkType')))
            if not check_res['res']:
                return jsonify({
                    'code': 1,
                    'msg': check_res['msg'],
                    'data': None
                })
            progress_data = check_progress(params.get('archivesId'), params.get('checkType'))
            if not progress_data['data']:
                return jsonify({
                    'msg': progress_data['msg'],
                    'code': 1
                })
            # 创建问询档案
            data_={
                #'inspection_log_id': '',
                'archives_id': params.get('archivesId'),
                'type': params.get('checkType'),
                'ybzz_yjdzhx': params.get('ybzzYjdzhx'),
                'ybzz_ks': params.get('ybzzKs'),
                'ybzz_ex': params.get('ybzzEx'),
                'ybzz_fl': params.get('ybzzFl'),
                'ybzz_sfbbs': params.get('ybzzSfbbs'),
                'ybzz_nxgnyc': params.get('ybzzNxgnyc'),
                'ybzz_ot': params.get('ybzzOt'),
                'ybzz_fg': params.get('ybzzFg'),
                'ybzz_xs': params.get('ybzzXs'),
                'ybzz_xxbjs': params.get('ybzzXxbjs'),
                'ybzz_gzmxyc': params.get('ybzzGzmxyc'),
                'ybzz_ch': params.get('ybzzCh'),
                'ybzz_yt': params.get('ybzzYt'),
                'ybzz_dxt': params.get('ybzzDxt'),
                'ybzz_sszc': params.get('ybzzSszc'),
                'ybzz_xm': params.get('ybzzXm'),
                'ybzz_fz': params.get('ybzzFz'),
                'ybzz_hd': params.get('ybzzHd'),
                'ybzz_xj': params.get('ybzzXj'),
                'hospital_id': 1
            }
            main_id = odoo.env['inspection.inquiries'].create(data_)
            create_event = event_type.OperationLogEvent('新增问询', '档案id:{}'.format(params.get('archivesId')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件

            logId = None
            if check_res['logId']:
                logId = check_res['logId']
                # 更新log表
                odoo.env['inspection.log'].write(logId, {
                    'wx_id': main_id
                })
                create_event = event_type.OperationLogEvent('更新log记录', 'logid:{}, wx_id{}'.format(logId,main_id))
                message_bus = MessageBusManager().get_message_bus()
                message_bus.handle(create_event)  # 发布事件
            else:
                # 创建检查记录
                check_data_ = {
                    'archives_id': params.get('archivesId'),
                    'type': params.get('checkType'),
                    'wx_id': main_id,
                    'state': '0'
                }
                logId = odoo.env['inspection.log'].create(check_data_)
                create_event = event_type.OperationLogEvent('创建检查记录', '档案id:{},wx_id{}'.format(params.get('archivesId'),main_id))
                message_bus = MessageBusManager().get_message_bus()
                message_bus.handle(create_event)  # 发布事件
            u_data_ = {'inspection_log_id': logId}
            data_u = odoo.env['inspection.inquiries'].write(main_id, u_data_)
            check_physical(int(params.get('archivesId')), params.get('checkType'))
            return jsonify({'code': 0, 'msg': 'success', 'data': {'logId': logId,'id': main_id}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class AskResultUpdateAPI(Resource):
    """
    修改问询或历史记录
    :request: put
    :param ybzzYjdzhx: 夜间端坐呼吸
    :param ybzzKs: 咳嗽
    :param ybzzEx: 恶心
    :param ybzzFl: 乏力
    :param ybzzSfbbs: 上腹部不适
    :param ybzzNxgnyc: 凝血功能异常
    :param ybzzOt: 呕吐
    :param ybzzFg: 发绀
    :param ybzzXs: 消瘦
    :param ybzzXxbjs: 血小板减少
    :param ybzzGzmxyc: 肝脏酶学异常
    :param ybzzCh: 出汗
    :param ybzzYt: 眼突
    :param ybzzDxt: 低血糖
    :param ybzzSszc: 双手震颤
    :param ybzzXm: 胸闷
    :param ybzzFz: 浮肿
    :param ybzzHd: 黄疸
    :param ybzzXj: 心悸
    :param logId: 历史记录时需传
    :param archivesId: 档案ID
    :param checkType: 1 初检 2 常规 3 产后42天
    :returns: json string
    """
    def put(self):
        try:
            odoo = OdooManager().get_instance()
            params = request.json
            # 参数校验
            req_params = ['archivesId','logId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            check_res = is_checking(params.get("archivesId"), params.get('checkType'))
            if not check_res['res'] and not params.get('history'):
                return jsonify({
                    'code': 1,
                    'msg': check_res['msg'],
                    'data': None
                })
            query_ = [
                ('archives_id', '=', int(params.get('archivesId'))),
                ('inspection_log_id', '=', int(params.get('logId')))
            ]
            inspection_inquiries = odoo.env['inspection.inquiries'].search(query_)
            if not inspection_inquiries:
                return jsonify({'code': 40005, 'msg': error_code[40005]})     
            # 修改问询或历史记录
            data_={
                'inspection_log_id': int(params.get('logId')),
                'archives_id': params.get('archivesId'),
                'type': params.get('checkType'),
                'ybzz_yjdzhx': params.get('ybzzYjdzhx'),
                'ybzz_ks': params.get('ybzzKs'),
                'ybzz_ex': params.get('ybzzEx'),
                'ybzz_fl': params.get('ybzzFl'),
                'ybzz_sfbbs': params.get('ybzzSfbbs'),
                'ybzz_nxgnyc': params.get('ybzzNxgnyc'),
                'ybzz_ot': params.get('ybzzOt'),
                'ybzz_fg': params.get('ybzzFg'),
                'ybzz_xs': params.get('ybzzXs'),
                'ybzz_xxbjs': params.get('ybzzXxbjs'),
                'ybzz_gzmxyc': params.get('ybzzGzmxyc'),
                'ybzz_ch': params.get('ybzzCh'),
                'ybzz_yt': params.get('ybzzYt'),
                'ybzz_dxt': params.get('ybzzDxt'),
                'ybzz_sszc': params.get('ybzzSszc'),
                'ybzz_xm': params.get('ybzzXm'),
                'ybzz_fz': params.get('ybzzFz'),
                'ybzz_hd': params.get('ybzzHd'),
                'ybzz_xj': params.get('ybzzXj')
            }
            odoo.env['inspection.inquiries'].write(inspection_inquiries,data_)
            create_event = event_type.OperationLogEvent('修改问询或历史记录', '档案id:{}'.format(params.get('archivesId')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            if not params.get('history'):
                check_physical(int(params.get('archivesId')), params.get('checkType'))
            return jsonify({'code': 0, 'msg': 'success', 'data': {'logId': params.get('logId'),'id': inspection_inquiries[0]}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class AskResultQueryListAPI(Resource):
    """
    查询问询记录回显及历史
    :request: get
    :param archivesId: 档案ID
    :param checkType: 1 初检 2 常规 3 产后42天
    :param logId: 针对历史记录的需要传
    :param type: NULL 不区分 0 在途 1完成
    :returns: json string
    """
    def get(self):
        try:
            #  获取问询记录回显及历史
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            query_ = []
            if  params.get('archivesId'):
                query_.append(('archives_id', '=', int(params.get('archivesId'))))
            if  params.get('checkType'):
                query_.append(('type', '=', params.get('checkType')))
            if  params.get('logId'):
                c_query_ = [
                    ('state', '=', '1'),
                    ('archives_id', '=', int(params.get('archivesId'))),
                    ('id', '=', int(params.get('logId')))
                ]
                inspection_log = odoo.env['inspection.log'].search_read(c_query_, ['wx_id'])
                if inspection_log:
                    inspection_log = inspection_log.pop()
                    query_.append(('id', '=', int(inspection_log['wx_id'][0])))
            else:
                # 查询档案在途的初检档案
                res = odoo.env['inspection.log'].search_read([
                    ('archives_id', '=', int(params.get('archivesId'))),
                    ('state', '=', '0'),
                    ('type', '=', params.get('checkType'))
                ])
                if (res):
                    res = res.pop()
                    if (res['wx_id']):
                        # 将问询Id append到查询条件中去
                        query_.append(('id', '=', int(res['wx_id'][0])))
                    else:
                        return {
                            'msg': 'success',
                            'code': 0,
                            'data': None
                        }
                else:
                    return {
                        'msg': 'success',
                        'code': 0,
                        'data': None
                    }
            inspection_inquiries = odoo.env['inspection.inquiries'].search_read(query_)
            data_ = {}
            if inspection_inquiries:
                inspection_inquiries = inspection_inquiries.pop()
                data_ = {
                    'ybzzYjdzhx': inspection_inquiries['ybzz_yjdzhx'],
                    'ybzzKs': inspection_inquiries['ybzz_ks'],
                    'ybzzEx': inspection_inquiries['ybzz_ex'],
                    'ybzzFl': inspection_inquiries['ybzz_fl'],
                    'ybzzSfbbs': inspection_inquiries['ybzz_sfbbs'],
                    'ybzzNxgnyc': inspection_inquiries['ybzz_nxgnyc'],
                    'ybzzOt': inspection_inquiries['ybzz_ot'],
                    'ybzzFg': inspection_inquiries['ybzz_fg'],
                    'ybzzXs': inspection_inquiries['ybzz_xs'],
                    'ybzzXxbjs': inspection_inquiries['ybzz_xxbjs'],
                    'ybzzGzmxyc': inspection_inquiries['ybzz_gzmxyc'],
                    'ybzzCh': inspection_inquiries['ybzz_ch'],
                    'ybzzYt': inspection_inquiries['ybzz_yt'],
                    'ybzzDxt': inspection_inquiries['ybzz_dxt'],
                    'ybzzSszc': inspection_inquiries['ybzz_sszc'],
                    'ybzzXm': inspection_inquiries['ybzz_xm'],
                    'ybzzFz': inspection_inquiries['ybzz_fz'],
                    'ybzzHd': inspection_inquiries['ybzz_hd'],
                    'ybzzXj': inspection_inquiries['ybzz_xj'],
                    'logId': inspection_inquiries['inspection_log_id'][0]
                }
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

